package com.ruoyi.hrmanagement.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.hrmanagement.bean.ResponseData;
import com.ruoyi.hrmanagement.bean.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.hrmanagement.mapper.ContractWorkerMapper;
import com.ruoyi.hrmanagement.domain.ContractWorker;
import com.ruoyi.hrmanagement.service.IContractWorkerService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 合同工Service业务层处理
 * 
 * @author wjj
 * @date 2024-09-13
 */
@Service
public class ContractWorkerServiceImpl implements IContractWorkerService 
{
    @Autowired
    private ContractWorkerMapper contractWorkerMapper;

    /**
     * 查询合同工
     * 
     * @param id 合同工主键
     * @return 合同工
     */
    @Override
    public ContractWorker selectContractWorkerById(Long id)
    {
        return contractWorkerMapper.selectContractWorkerById(id);
    }

    /**
     * 查询合同工列表
     * 
     * @param contractWorker 合同工
     * @return 合同工
     */
    @Override
    public List<ContractWorker> selectContractWorkerList(ContractWorker contractWorker)
    {
        return contractWorkerMapper.selectContractWorkerList(contractWorker);
    }

    /**
     * 新增合同工
     * 
     * @param contractWorker 合同工
     * @return 结果
     */
    @Override
    public int insertContractWorker(ContractWorker contractWorker)
    {
        return contractWorkerMapper.insertContractWorker(contractWorker);
    }

    /**
     * 修改合同工
     * 
     * @param contractWorker 合同工
     * @return 结果
     */
    @Override
    public int updateContractWorker(ContractWorker contractWorker)
    {
        return contractWorkerMapper.updateContractWorker(contractWorker);
    }

    /**
     * 批量删除合同工
     * 
     * @param ids 需要删除的合同工主键
     * @return 结果
     */
    @Override
    public int deleteContractWorkerByIds(Long[] ids)
    {
        return contractWorkerMapper.deleteContractWorkerByIds(ids);
    }

    /**
     * 删除合同工信息
     * 
     * @param id 合同工主键
     * @return 结果
     */
    @Override
    public int deleteContractWorkerById(Long id)
    {
        return contractWorkerMapper.deleteContractWorkerById(id);
    }


    @Override
    @Transactional
    public ResponseData<Object> insertContractWorkers(List<ContractWorker> contractWorkerList) {
        List<ContractWorker> validContractWorkers = new ArrayList<>();
        StringBuilder errorMsg = new StringBuilder();
        ResponseData< Object> responseData = new ResponseData<>();
//        Map<String, Object> result = new HashMap<>();  // 用于存放成功插入的数量和错误信息

        for (int i = 0; i < contractWorkerList.size(); i++) {
            ContractWorker worker = contractWorkerList.get(i);

            // 校验：如果该行的所有字段都为空，则认为读到末尾，停止读取
            if (isAllFieldsEmpty(worker)) {
                break;
            }

            // 校验：姓名、性别、出生日期、身份证号 任何一个为空就跳过
            if (worker.getName() == null || worker.getName().trim().isEmpty() ||
                    worker.getGender() == null || worker.getGender().trim().isEmpty() ||
                    worker.getBirthday() == null || worker.getBirthday().trim().isEmpty() ||
                    worker.getIdCardNumber() == null || worker.getIdCardNumber().trim().isEmpty()) {

                errorMsg.append("第 ").append(i + 1).append(" 行的姓名、性别、出生日期或身份证号不能为空\n;");
                continue; // 跳过该行数据
            }

            // 校验身份证号是否符合18位
            if (worker.getIdCardNumber().length() != 18) {
                errorMsg.append("第 ").append(i + 1).append(" 行的身份证号不符合18位\n;");
                continue; // 跳过该行
            }

            // 调用 existsByIdCardNumber 方法
            Integer exists = contractWorkerMapper.existsByIdCardNumber(worker.getIdCardNumber().trim());

            // 如果 exists 不为 null，说明身份证号已存在
            if (exists != null) {
                errorMsg.append("第 ").append(i + 1).append(" 行的身份证号已存在\n;");
                continue; // 跳过该行
            }

            // 所有校验通过，将该数据加入有效数据列表
            validContractWorkers.add(worker);
        }

        // 如果有有效数据，则执行插入操作
        if (!validContractWorkers.isEmpty()) {
            contractWorkerMapper.batchInsert(validContractWorkers); // 批量插入有效数据
        }

        // 将插入的成功数据量和错误信息存入 result
//        result.put("insertedCount", validContractWorkers.size());  // 插入的数量
//        result.put("errorMessages", errorMsg.toString());  // 错误信息

        // 返回结果
        if (!validContractWorkers.isEmpty()) {
            responseData.setErrorCode(ResultCode.SUCCESS.getCode());
            responseData.setData("成功插入了" + validContractWorkers.size() + "条;错误信息:" + errorMsg);  // 将结果数据设置为返回值
            responseData.setMsg(ResultCode.SUCCESS.getMessage());
        } else {
            responseData.setErrorCode(ResultCode.COMMON_FAIL.getCode());
            responseData.setData( "导入失败!\n错误信息:" + errorMsg);  // 即使失败，也返回错误信息
            responseData.setMsg(ResultCode.COMMON_FAIL.getMessage());
        }

        return responseData;  // 返回结果
    }


    /**
     * 判断合同工所有字段是否为空
     *
     * @param worker 合同工实体
     * @return 如果所有字段都为空，返回 true；否则返回 false
     */
    private boolean isAllFieldsEmpty(ContractWorker worker) {
        return (worker.getName() == null || worker.getName().trim().isEmpty()) &&
                (worker.getGender() == null || worker.getGender().trim().isEmpty()) &&
                (worker.getBirthday() == null || worker.getBirthday().trim().isEmpty()) &&
                (worker.getGrade() == null || worker.getGrade().trim().isEmpty()) &&
                (worker.getPersonnelClassification() == null || worker.getPersonnelClassification().trim().isEmpty()) &&
                (worker.getEducation() == null || worker.getEducation().trim().isEmpty()) &&
                (worker.getDuty() == null || worker.getDuty().trim().isEmpty()) &&
                (worker.getTitle() == null || worker.getTitle().trim().isEmpty()) &&
                (worker.getNativePlace() == null || worker.getNativePlace().trim().isEmpty()) &&
                (worker.getMinority() == null || worker.getMinority().trim().isEmpty()) &&
                (worker.getJoinPartyDate() == null || worker.getJoinPartyDate().trim().isEmpty()) &&
                (worker.getPoliticalOutlook() == null || worker.getPoliticalOutlook().trim().isEmpty()) &&
                (worker.getFullTimeQualification() == null || worker.getFullTimeQualification().trim().isEmpty()) &&
                (worker.getFullTimeDegree() == null || worker.getFullTimeDegree().trim().isEmpty()) &&
                (worker.getFullTimeGraduateSchoolSpecialty() == null || worker.getFullTimeGraduateSchoolSpecialty().trim().isEmpty()) &&
                (worker.getJobEducationQualification() == null || worker.getJobEducationQualification().trim().isEmpty()) &&
                (worker.getJobGraduateSchoolSpecialty() == null || worker.getJobGraduateSchoolSpecialty().trim().isEmpty()) &&
                (worker.getIdCardNumber() == null || worker.getIdCardNumber().trim().isEmpty()) &&
                (worker.getPhoneNumber() == null || worker.getPhoneNumber().trim().isEmpty()) &&
                (worker.getSpousalWorkplace() == null || worker.getSpousalWorkplace().trim().isEmpty()) &&
                (worker.getSpousalDuty() == null || worker.getSpousalDuty().trim().isEmpty()) &&
                (worker.getParentWorkplace() == null || worker.getParentWorkplace().trim().isEmpty()) &&
                (worker.getParentDuty() == null || worker.getParentDuty().trim().isEmpty()) &&
                (worker.getChildrenWorkplace() == null || worker.getChildrenWorkplace().trim().isEmpty()) &&
                (worker.getChildrenDuty() == null || worker.getChildrenDuty().trim().isEmpty()) &&
                (worker.getFormalEstablishment() == null || worker.getFormalEstablishment().trim().isEmpty()) &&
                (worker.getParentName() == null || worker.getParentName().trim().isEmpty()) &&
                (worker.getChildrenName() == null || worker.getChildrenName().trim().isEmpty()) &&
                (worker.getYearPublicHoliday() == null || worker.getYearPublicHoliday().trim().isEmpty()) &&
                (worker.getRestPublicHoliday() == null || worker.getRestPublicHoliday().trim().isEmpty()) &&
                (worker.getIsDeleted() == null) &&
                (worker.getIsLocked() == null);
    }


}
